package education.social;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;



public class User_Service extends Service {

	final static int mMaxRequestCount = 4;
	
	int REQUEST_ID_INVALID = 0;
	int REQUEST_ID_START = 1;
	int REQUEST_ID_STARTED = 2;
	int REQUEST_ID_STOPPED = 3;
	
	private int[] mRequestId = new int[mMaxRequestCount];
	
	private int current_request_id = -1;
	private boolean mIsThreadBusy = false;
	private int mThreadExistFlag = 0;

	Thread mServiceThread;
	Handler mHandler;
	 
	UserInfo mUserInfo;
	
	Runnable threadRunnable = new Runnable()
	{
		//just one request task is activity,start another task just when pre-task completed
		public void run() {
			
			if(mIsThreadBusy)
				return;
			
			for(int i = 0; i < mMaxRequestCount; i++)
			{
				if(mRequestId[i] == REQUEST_ID_START)
				{
					Message msg = new Message();
					msg.what = 0;
					msg.arg1 = i;
					
					try {
						mQueryService(msg.arg1);
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					mHandler.sendMessage(msg);

					mRequestId[i] = REQUEST_ID_STARTED;
					mIsThreadBusy = true;
					return;
				}
			}
		}
	};
	
	private Thread mCreateThread()
	{
		if(mServiceThread == null)
		{
			mServiceThread = new Thread(threadRunnable);
			mThreadExistFlag = 1;
		}
		
		return mServiceThread;
	}
	
	public void StartQuest(int quest_id)
	{
		for(int i = 0; i < mMaxRequestCount; i++)
		{
			if(i == quest_id)
			{
				if(mRequestId[quest_id] != REQUEST_ID_STARTED)
					mRequestId[quest_id] = REQUEST_ID_START;
			}else
			{
				if(mRequestId[i] == REQUEST_ID_START)
					mRequestId[i] = REQUEST_ID_STOPPED;
			}
		}
		mCreateThread();
		mServiceThread.start();
	};
	
	private String mGetCompletionHttpHead(int request_id, String Httphead)
	{
		String CompletionHttpHead = null;
		switch(request_id)
		{
		case 0:
			CompletionHttpHead = Httphead + "LogonAction";//UserInfo.mMainListId;
			break;
		case 1:
			CompletionHttpHead = Httphead + UserInfo.mFriendListId;
			break;
		case 2:
			CompletionHttpHead = Httphead + UserInfo.mNearbyPeopleId;
			break;
		case 3:
			CompletionHttpHead = Httphead + UserInfo.mUserInfoId;
			break;
			
		default:
				break;
		}
		
		return CompletionHttpHead;
	}
	
	private void mQueryService(int request_id) throws ClientProtocolException, IOException
	{
		//Toast.makeText(getApplicationContext(),
		//		"mQueryService get in  Succeed", Toast.LENGTH_LONG).show();
		
		Message msg = new Message();
		
		current_request_id = request_id;
		
		String serviceHead = mGetCompletionHttpHead(request_id, mUserInfo.mGetServiceHead());
		
		//now just support POST method request
		HttpPost httpRequestPost = new HttpPost(serviceHead);
				
		List <NameValuePair> params = new ArrayList <NameValuePair>();
					
		params.add(new BasicNameValuePair("account", "wujiangwei"));
		params.add(new BasicNameValuePair("password", "123456"));
		
		//params.add(new BasicNameValuePair("string", mUserInfo.mGetUserAccount()));
		
		//send HTTP request

		msg.arg1 = request_id;
		
		httpRequestPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		
		//HTTP response
		HttpResponse myHttpResponse = new DefaultHttpClient().execute(httpRequestPost);
		
		if(myHttpResponse.getStatusLine().getStatusCode() == 200)
		{
			msg.what = 1;
			mRequestId[current_request_id] = REQUEST_ID_INVALID;
			current_request_id = -1;
			//TODO
		}else
		{
			msg.what = 0;
			mRequestId[current_request_id] = REQUEST_ID_INVALID;
			current_request_id = -1;
		}
		
		mHandler.sendMessage(msg);
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		IBinder myBind = new LocalBinder();
		
		Toast.makeText(getApplicationContext(), "binding OK", Toast.LENGTH_SHORT).show();
		
		return myBind;
	};
	
	public class LocalBinder extends Binder {
		User_Service getService() {
            // Return this instance of LocalService so clients can call public methods
            return User_Service.this;
        }
	};
	
	public class UserHandler extends Handler
	{
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what)
			{
			case 0:
				Toast.makeText(getApplicationContext(),
	    				"Get Http Post Response Failed", Toast.LENGTH_LONG).show();
				break;
			case 1:
				Toast.makeText(getApplicationContext(),
	    				"Get Http Post Response Succeed", Toast.LENGTH_LONG).show();
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}
	
	@Override
	public void onCreate()
	{
		super.onCreate();
		
		int i = 0;
		for(; i < mMaxRequestCount; i++)
		{
			mRequestId[i] = REQUEST_ID_INVALID;
		}
		
		mHandler =new UserHandler();
		mUserInfo = mUserInfo.mGetUserInfoInstance(this);
	};
	
	
	@Override
	public void onDestroy()
	{
		for(int i = 0; i < mMaxRequestCount; i++)
			mRequestId[i] = REQUEST_ID_INVALID;
		
		if(mThreadExistFlag == 1)
		{
			mServiceThread.destroy();
			mThreadExistFlag = 0;
			mServiceThread = null;
		}	
		super.onDestroy();
	};
	
}